package ute.mvc.tiles.viewpreparer;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.tiles.Attribute;
import org.apache.tiles.AttributeContext;
import org.apache.tiles.preparer.ViewPreparer;
import org.apache.tiles.request.Request;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import ute.mvc.model.Course;
import ute.mvc.model.User;
import ute.mvc.util.Item;

public class PortalVerticalMenuPreparer implements ViewPreparer {

	public void execute(Request request, AttributeContext attributeContext) {
		// TODO Auto-generated method stub
		// Get session
		HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = httpRequest.getSession();

		// Menu
		/*String requestAddress = httpRequest.getRequestURL().toString();
		if (requestAddress.contains("/lecturer"))
			type = 2;
		else if (requestAddress.contains("/portal"))
			type = 1;
		else
			type = 3;*/

		//Work with session
		User user = (User) session.getAttribute("user");
		int type = user.getRole();
		attributeContext.putAttribute("type", new Attribute(type), true);
		attributeContext.putAttribute("user", new Attribute(user), true);
		
		//Dynamic
		
		int changeMenu = 0;
		String[] url = {};
		String requestAddress = httpRequest.getRequestURL().toString();
		if(type == 1){
			//Do nothing
		}else{
			int count = StringUtils.countOccurrencesOf(requestAddress, "/");
			System.out.println(requestAddress);
			if(count >= 8){
				changeMenu = 1;
				url = requestAddress.split("/");
			}
		}
		attributeContext.putAttribute("change", new Attribute(changeMenu), true);
		attributeContext.putAttribute("url", new Attribute(url), true);
	}
}
